package main

import (
	"fmt"
	"os"
	"os/signal"
	"sync"
	"time"
)

var wg sync.WaitGroup

func mainv1() {
	fmt.Println("server start")
	c := make(chan os.Signal, 1)
	signal.Notify(c)
	select {
	case sg := <-c:
		fmt.Println(sg == os.Interrupt)
		fmt.Println(sg.String())
	}
}

func shutdown() {
	time.Sleep(time.Second * 10)
	fmt.Println("server exit gracefully")
	wg.Done()
}

func main() {
	fmt.Println("server start")
	wg.Add(1)
	c := make(chan os.Signal, 1)
	signal.Notify(c)
	go func() {
		select {
		case sg := <-c:
			fmt.Println(sg == os.Interrupt)
			fmt.Println(sg.String())
			go func() {
				// listen interrupt signal twice
				select {
				case sg2 := <-c:
					// Forced shutdown
					switch sg2 {
					case os.Interrupt:
						fmt.Println("server shutdown forcibly")
						wg.Done()
					}
				}
			}()

			// shutdown gracefully
			shutdown()
		}
	}()
	wg.Wait()
}
